class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        
        root.left,root.right = root.right, root.left

        self.invertTree(root.left)

        self.invertTree(root.right)
    
        return root

    def invertTree2(self, root: TreeNode) -> TreeNode:
        if not root:
            return None

        queue = [root]
        while queue:
            node = queue.pop(0)  # 取出队列头节点
            # 交换当前节点的左右子节点
            node.left, node.right = node.right, node.left
            # 将非空子节点加入队列
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

        return root
    
